package com.yexx.starter.ribbon.filter;

import com.yexx.core.constant.CommonConstants;
import com.yexx.core.holder.LbIsolationContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Description: 负载均衡隔离规则过滤器
 *
 * @author: zuomin (myleszelic@outlook.com)
 * @date: 2020/12/07-16:59
 */
@ConditionalOnClass(value = {Filter.class})
public class LbIsolationFilter extends OncePerRequestFilter {

    @Value("${" + CommonConstants.RIBBON.CONFIG_RIBBON_ISOLATION_ENABLED + ":false}")
    private boolean enableIsolation;

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        return super.shouldNotFilter(request);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            String version = request.getHeader(CommonConstants.RIBBON.LB_VERSION_HEADER);
            if(StringUtils.isNotEmpty(version)){
                LbIsolationContextHolder.setVersion(version);
            }
            filterChain.doFilter(request, response);
        } finally {
            LbIsolationContextHolder.clear();
        }
    }
}
